<?php

session_start(); //початок сесії

class User extends Controller 
{

		function Intro()
		{
			parent::Controller();
		}//end method

	function index()
		{
			redirect("welcome");
		}//end method
		
		function login()
		{
			$data		= array();//ініціалізація массиву
			$this->load->model('common');
			$now		= date('Y-m-d h:i:s');//створення поточної дати
			$datas	= $this->common->basicvars();
			$data	= $datas;
			if(isset($_POST['login_submit']))//перевірки форми входу на відправлення данних
				{
					$email		= trim($_POST['email']);
					$password 	= md5(trim($_POST['pass']));
					
					//валідація робиться тут
					if($email == '')
						$error	= "Помилка: Невказано поштову скриньку!";
					elseif($password == '')
						$error	= "Помилка: Невказано пароль";
					else//якщо проста перевірка закінчена
						{
							$condition = "email = '$email' AND password='$password' AND user_status='active'";//creat condition for record exit query
							$fieldName = "user_id";
							//перевірка паролю та електронної скриньки на існування
							if(IsRecordExist4Add('users',$fieldName,$condition))
								{
									$fieldList			= ' user_id ';
									$user_rs			= getRow('users', $fieldList, $condition);
									
									//обновлення останньої активності користувача в таблиці users
									updateRecords('users',"last_login='$now'","user_id='$user_rs[user_id]'");
									updateRecords('users',"logged_in='1'","user_id='$user_rs[user_id]'");
								
									$this->session->expire_cookie(false);
									
									$mysess = array(
									   'user_id'  => ''.$user_rs['user_id'].'',
									   'loginUrl'     => '/',
									   'user_data',  'user_id_'.$userId.''
								   );
									
									$this->session->set_userdata($mysess);
																	
									if($this->session->userdata('loginUrl'))
										{
											$loginUrl	= $this->session->userdata('loginUrl');
											header("Location: ".$loginUrl);
										}
									else
										redirect("welcome");
								}
							else
								$error	= "Помилка: Невірно вказано поштову скриньку або пароль!";
						}
						
				}//end login
			//echo site_url();
			if($error!='')
				{
			
					$data['error']=	'<div class="msg-error">'.$error.'</div>';
				}

			$data['siteUrl']		= site_url();
			$data['center_login']	= true;
			$this->smartyextended->view('user/login',$data);
		}//end method	
	
	function logout()
		{
			$this->load->helper('common');	
			updateRecords('users',"logged_in='0'","user_id='".$this->session->userdata('user_id')."'");			
			$this->session->unset_userdata('user_id');
			$this->session->unset_userdata('loginUrl');

			$this->session->sess_destroy();

			redirect();
		}//end method
		
	function register()
		{
			$this->load->model('common');
			$datas	= $this->common->basicvars();
			$data	= array();
			$data	= $datas;
			$data['currentPage']	= base_url();
			$this->smartyextended->view('user/register',$data);
		}//end method
		
	function forgot()
		{
			$this->loadSettings();
			$data	= $this->common->basicvars();
			if($_POST['reset_submit'])
				{
					$email		= trim($_POST['reset_email']);
					if($email=='')
						$result	= '<div class="msg-error">Помилка: Невказана поштова скринька</div>';
					elseif($email!='' and !isValidEmail($email))
						$result	= '<div class="msg-error">Помилка: Невірний формат поштової скриньки</div>';
					elseif($email!='')
						{
							$isExist	= getTotRec("user_id","users","email='$email'");
							if($isExist)
								{
									$usrRs			= getRow("users","username","email='$email'");
									$randNo			= rand(100000,999999);
									$newPassword	= md5($randNo);
									$friendsUrl	= base_url().'friends/';
									$this->load->library('email');	//loads email library
									$config['mailtype'] = 'html';
									$this->email->initialize($config);
									$this->email->from($adminEmail, $siteTitle);
									$this->email->to($email);
									$senderName		= ucwords($usrRs[username]);
									$mailSubject	= 'Відновлення паролю';
									$mailContent	= 'Привіт<br><br>'.$senderName.'<br><br>
													Ви нещодавно запросили новий пароль. Використовуйте наступний пароль для входу до мережі.<br<br>
													Ваш новий пароль : '.
													$randNo.'<br><br>
													З повагою,<br>
													'.$adminName;
									$this->email->subject($mailSubject);											//set subject to send mail
									$this->email->message($mailContent);											//set message to send mail
									//send mail
									if($this->email->send())
										{
											updateRecords("users","show_password='$randNo', password='$newPassword'","email='$email'");
											$data['sent_success']	= true;
										}
									else
										$result	= '<div class="msg-error">Помилка: Невдалося відправити повідомлення</div>';
								}
							else
								$result	= '<div class="msg-error">Помилка: Користувач з такою поштовою скринькою не знайдений</div>';
						}
					if($result!='')
						$data[result]	= 	$result;
				}
			$data['forgot_password']	= true;
			$this->smartyextended->view('user/forgot',$data);
		}//end method
	function profile()
		{
			$this->loadSettings();
			$datas		= $this->common->authenticate();

			global $userId,$now;
			if(count($datas)<1)
				{
					$datas	= $this->common->basicvars();
					$data	= $datas;
					$data['siteUrl']		= site_url();
					$data['center_login']	= true;
					$this->smartyextended->view('user/login',$data);
				}
			else
				{
					$data		= array();
					$data		= $datas;
					
					$profileId		= $this->uri->segment(3);//get profile id as user id
					$requestType		= $this->uri->segment(4);//get profile id as user id
					$profileExist	= getTotRec("user_id","users","user_id='$profileId'");//checks whether user exist or not
					
					$data['count_friends_request']	= $this->common->countFriendRequest($userId);
					$data['count_new_msg']	= $this->common->countNewMsg($userId);
					$data['count_wall_msg']	= $this->common->countWallMsg($profileId);
					$data['count_out_request']	= $this->common->countOutRequest($userId);
					$this->session->set_userdata('user_data',  'user_id_'.$userId.'');
					updateRecords('users','logged_in="1"','user_id="'.$userId.'"');
					
					if($profileExist)//якщо профіль існує
						{

							$isPhotoExist	= getTotRec("picture_id","picture_profile","picture_path<>'' AND user_id='$profileId'");
							
							if($isPhotoExist) {
								$data['user_avatar']		= '<img src="'.$this->common->getLargeAvatar($profileId).'" border="0">';//отримання фото користувача
							} else {
								$data['user_avatar']		= '<div id="nophoto"><img src="'.$this->common->getLargeAvatar($profileId).'" border="0"></div>';//get user photo
							}
							
							$data['user_actions']		= $this->showActions($profileId, $userId);
							$data['profile_id']			= $profileId;
							$data['user_name']			= ucwords($this->common->getUsername($profileId));

							$data['friends']			= $this->showFriends($profileId,$userId);			//show friends on profile page
							$data['online_friends']		= $this->showOnlineFriends($profileId,$userId);			//show friends on profile page
							
							$data['wall_post']			= $this->showWall($profileId,$userId);//get contact information
								
							$data['user_status']		= $this->showStatus($profileId,$userId);
							$data['screen_select']		= $this->userStatusSelect($profileId);
							
							$data['user_basic_info']	= $this->userBasicInfo($profileId);
							$data['personalInfo']		= $this->getPersonalInfo($profileId,$userId);
							$data['user_information']	= $this->userInformation($profileId,$userId);//отримання контакної інформації
							$data['work_information']	= $this->workInformation($profileId,$userId);//get work information
							$data['offline']			= $this->common->offline($profileId, 'profile');
							$data['view_profile']		= true;
							$this->smartyextended->view('user/profile',$data);
								
							
						}
						else {
							redirect('welcome');
						}
					
				}
		}//end method

	function showStatus($profileId, $userId)
		{
			$this->load->helper('smiley');
			$rs	= getRow("users","screen_status_id,screen_status_changed_date","user_id='$profileId'");
			if($rs['screen_status_id']!='')
				{
					$status		= parse_smileys($rs['screen_status_id'], "http://demo.maax.ws/application/images/smileys/");
					
					if ($profileId == $userId)
					$status .= ' <p><a href="javascript: void(0);" style="text-decoration:none;" onclick="show_div(\'screen_status_change_div\');close_div(\'screen_status_div\');"><b>[ змінити статус ]</b></a></p>';
				}
			else 
				{
					if ($profileId == $userId)
					$status	= '<a href="javascript: void(0);" style="text-decoration:none;" onclick="show_div(\'screen_status_change_div\');close_div(\'screen_status_div\');"><b>[ змінити статус ]</b></a>';
					else
					$status	= '';
				}
			return $status;
		}

	function userStatusSelect($profileId)
		{
			$rs	= getRow("users","screen_status_id,screen_status_changed_date","user_id='$profileId'");
			$extra			= 'onblur="changeUserStatus(\''.$profileId.'\',\''.base_url().'\',\'store\')"';
			$screenSelect	= '<input type="text" maxlength="255" id="screenStatusSelect" value="'.$rs['screen_status_id'].'" class="text" style="width: 150px;" '.$extra.'>';
			return $screenSelect;
		}

	function userBasicInfo($profileId)
		{
			$fieldList	= "sex_id,interested_in_id,relation_id,looking_for_id,city,birthday,birthday_visibility_id,political_id,religious_view";
			$rs			= getRow("general_profile",$fieldList,"user_id='$profileId'");

			if ($this->getSex($rs['sex_id'])!='' or $this->getInterestedIn($rs['interested_in_id'])!='' or $this->getRelation($rs['relation_id'])!='' or $this->getPoliticalView($rs['political_id'])!='' or $rs['religious_view']!='' or $this->getBirthday($rs['birthday_visibility_id'],$rs['birthday'])!='')
			$content 	= '';
			
			
			if($this->getSex($rs['sex_id'])!='')//підготовка статі
				$sex			= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Стать:</td><td><div class="profile_field_value"><a href="'.base_url().'search?submit_search=1&gender='.$rs['sex_id'].'">'.$this->getSex($rs['sex_id']).'</a></div></td></tr>';
			if($this->getInterestedIn($rs['interested_in_id'])!='')//підготовка інформації ким цікавиться
				$interestedIn	= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Цікавлюсь:</td><td><div class="profile_field_value">'.$this->getInterestedIn($rs['interested_in_id']).'</div></td></tr>';
			if($this->getLookingFor($rs['looking_for_id'])!='')
				$lookingFor		= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Шукаю:</td><td valign="top"><div class="profile_field_value">'.$this->getLookingFor($rs['looking_for_id']).'</div></td></tr>';
			if($this->getRelation($rs['relation_id'])!='')
				$relation		= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Стосунки:</td><td><div class="profile_field_value">'.$this->getRelation($rs['relation_id']).'</div></td></tr>';
				
				$homeTown	= $this->getCity($rs['city']);
			if(trim($homeTown)!='')
				$hometown	= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Звідки:</td><td><div class="profile_field_value">'.$homeTown.'</div></td></tr>';

			if($this->getPoliticalView($rs['political_id'])!='')
				$politicalView	= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Політичні погляди:</td><td><div class="profile_field_value">'.$this->getPoliticalView($rs['political_id']).'</div></td></tr>';
			if($rs['religious_view']!='')//отримання релігійних поглядів
				$religiousView	= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Релігійні погляди:</td><td><div class="profile_field_value">'.$rs['religious_view'].'</div></td></tr>';
			$birthday	= $this->getBirthday($rs['birthday_visibility_id'],$rs['birthday']);
			$content	.= 	$sex.$birthday.$hometown.$relation.$interestedIn.$lookingFor.$politicalView.$religiousView;
			return $content;
		}

	function getRelation($relationId)
		{
			$relation	= '';
			if($relationId>0)//prepares relation status
				{
					$relRs			= getRow("relation_status","relation","relation_id=".$relationId);
					$relation		= $relRs['relation'];
				}
			return $relation;
		}

	function getSex($sexId)
	{
			$sex	= '';
			if($sexId>0)//prepares sex type
				{
					$relRs		= getRow("sex","sex","sex_id=".$sexId);
					$sex		= $relRs['sex'];
				}
			return $sex;
	}
	

	function getLookingFor($lookingForId)
		{
			$lookingFor	= '';
			if($lookingForId!='')//prepares looking for
				{
					$lookingId		= explode(",",trim($lookingForId,","));
					$lookingFor		= '';
					for($i=0;$i<count($lookingId);$i++)
						{
							$lookingRs		= getRow("looking_for","lookingfor","looking_id=".$lookingId[$i]);
							$lookingFor		.= $lookingRs['lookingfor'].'<br>';
						}
				}
			return $lookingFor;
		}
		

	function getInterestedIn($interestedInId)
		{
			$interestedIn	= '';
			if($interestedInId!='')//prepares interested in
				{
					$interestedId		= explode(",",trim($interestedInId,","));
					$interestedIn		= '';
					for($i=0;$i<count($interestedId);$i++)
						{
							$interestedRs		= getRow("interested_in","interestedin","interested_id=".$interestedId[$i]);
							$interestedIn		.= $interestedRs['interestedin'].'<br>';
						}
				}
			return $interestedIn;
		}

	function getPoliticalView($politicalId)
		{
			$polticalView	= '';
			if($politicalId>0)//prepares political views
				{
					$polRs			= getRow("political_views","political_view","political_id=".$politicalId);
					$politicalView	= $polRs['political_view'];
				}
			return $politicalView;
		}

	function getBirthday($visible,$bday)
		{
			$this->load->helper('date');
			
			$mn["01"]  = "січня";
			$mn["02"]  = "лютого";
			$mn["03"]  = "березня";
			$mn["04"]  = "квітня";
			$mn["05"]  = "травня";
			$mn["06"]  = "червня";
			$mn["07"]  = "липня";
			$mn["08"]  = "серпня";
			$mn["09"]  = "вересня";
			$mn["10"]  = "жовтня";
			$mn["11"]  = "листопада";
			$mn["12"]  = "грудня";
			
			$bsplit	= explode("-",$bday);
			if($visible==1 and $bday!='')//show full birthday
				$birthday	= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">День народження:</td><td>'.date("d ",mktime(0,0,0,$bsplit[1],$bsplit[0],$bsplit[2])).$mn[date("m", mktime(0,0,0,$bsplit[1],$bsplit[0],$bsplit[2]))].date(" Y р.",mktime(0,0,0,$bsplit[1],$bsplit[0],$bsplit[2])).'</td></tr>';//getting unix timestamp value
			elseif($visible==2 and $bday!='')//show day and month
				$birthday	= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">День народження:</td><td>'.date("d ",mktime(0,0,0,$bsplit[1],$bsplit[0],$bsplit[2])).$mn[date("m", mktime(0,0,0,$bsplit[1],$bsplit[0],$bsplit[2]))].'</td></tr>';//getting unix timestamp value
			elseif($visible==3)//dont show birthda
				$birthday	= '';
				
			return $birthday;

		}

	function getCity($citySymbol)
		{
			$city	= '';
			if($citySymbol!='')//prepares country
				{
					$rs			= getRow("city","city_name","city_symbol='$citySymbol'");
					$city	= $rs['city_name'];
				}
			return $city;
		}


	function userInformation($profileId,$userId)
		{

			$contactInfo	= $this->getContactInfo($profileId,$userId);
			$eduInfo		= $this->getEduInfo($profileId,$userId);
			
			
			if(($contactInfo!="") or ($eduInfo!=""))
			{
				$content	= $contactInfo.$personalInfo.$eduInfo;
			}
			return $content;
		}//userInformation()


	function getContactInfo($profileId,$userId)
		{
			$fieldList		= "mobile,land_line,address,website,icq, skype";
			$rs				= getRow("contact_profile",$fieldList,"user_id='$profileId'");
			$usrRs			= getRow("users","email","user_id='$profileId'");
			
			
				if ($rs['mobile']!='' or $rs['land_line']!='' or $rs['address']!='' or $rs['website']!='' or $usrRs['email']!='') {
				
					if($userId==$profileId) {
						$editUrl	= '<a href="'.base_url().'edit/contacts" style="text-decoration:none;">[ редагувати ]</a>';
					}
					
					$contactInfo .= '<tr><td colspan="2"><div class="profile_headline" style="padding-top: 10px;"><b>Контактна iнформацiя</b> '.$editUrl.'</div></td></tr>';
				}
				
				$contactInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Поштова скринька:&nbsp;</td><td><a href="mailto:'.$usrRs['email'].'">'.$usrRs['email'].'</a></td></tr>';

				if($rs['mobile']!='')
					$contactInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Номер мобільного:</td><td>'.$rs['mobile'].'</td></tr>';

				if($rs['land_line']!='')
					$contactInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Домашній телефон:</td><td>'.$rs['land_line'].'</td></tr>';

				if($rs['address']!='')
					$contactInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Адреса:</td><td>'.$rs['address'].'</td></tr>';
			
				if($rs['skype']!='')
					$contactInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Skype:</td><td><a href="callto:'.$rs['skype'].'">'.$rs['skype'].'</a></td></tr>';
			
				if($rs['icq']!='')
					$contactInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">ICQ:</td><td>'.$rs['icq'].'</td></tr>';
				
				if($rs['website']!='')
					$contactInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Веб-сторінка:</td><td><a href="http://'.$rs['website'].'">'.$rs['website'].'</a></td></tr>';

			return $contactInfo;
		}//getContactInfo()


	function getPersonalInfo($profileId,$userId)
		{
		
			$this->load->helper('typography');
			$this->load->helper('smiley');
			
			$personalInfo	= '';
			
			$fieldList		= "activities,interests,favorite_music,favorite_tv_shows,favorite_movies,favorite_books,favorite_quotes,about_me";
			$rs				= getRow("member_personal",$fieldList,"user_id='$profileId'");

			if($rs['activities']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Дiяльнiсть:</td><td>'.nl2br_except_pre($rs['activities']).'</td></tr>';
			if($rs['interests']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Iнтереси:</td><td>'.nl2br_except_pre($rs['interests']).'</td></tr>';
			if($rs['favorite_music']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Улюблена музика:</td><td>'.nl2br_except_pre($rs['favorite_music']).'</td></tr>';
			if($rs['favorite_movies']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Улюбленi фiльми:</td><td>'.nl2br_except_pre($rs['favorite_movies']).'</td></tr>';
			if($rs['favorite_tv_shows']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Улюбленi телешоу:</td><td>'.nl2br_except_pre($rs['favorite_tv_shows']).'</td></tr>';
			if($rs['favorite_books']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Улюбленi книги:</td><td>'.nl2br_except_pre($rs['favorite_books']).'</td></tr>';
			if($rs['favorite_quotes']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Улюбленi цитати:</td><td>'.parse_smileys(nl2br_except_pre($rs['favorite_quotes']), "http://demo.maax.ws/application/images/smileys/").'</td></tr>';
			if($rs['about_me']!='')
				$personalInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Про себе:</td><td>'.parse_smileys(nl2br_except_pre($rs['about_me']), "http://demo.maax.ws/application/images/smileys/").'</td></tr>';
			if($userId==$profileId)
				$editUrl	= '<a href="'.base_url().'edit/personal" style="text-decoration:none;">[ редагувати ]</a>';
			if($personalInfo!='')
				$personalInfo	= '<tr><td colspan="2"><div class="profile_headline" style="padding-top: 10px;"><b>Особиста iнформацiя</b> '.$editUrl.'</div></td></tr>'.$personalInfo;
			return $personalInfo;
		}//getPersonalInfo()


	function getEduInfo($profileId,$userId)
		{
			$fieldList		= "school_name,class_year,concentration1,class_year";
			$clgrs			= getRow("school_education",$fieldList,"user_id='$profileId'");
			$rs				= getRow("education_profile","high_school,datestamp","user_id='$profileId'");
			$usrRs			= getRow("users","email","user_id='$profileId'");
			$clgyear = substr($clgrs['class_year'], -2);
			
			if($clgrs['school_name']!="")
				$eduInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Вища освіта:</td><td>'.$clgrs['school_name'].' \''.$clgyear.'</td></tr>';
			if($clgrs['concentration1']!="")
				$eduInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Факультет:</td><td>'.$clgrs['concentration1'].'</td></tr>';
				
			if($rs['high_school']!="")
				$eduInfo	.= '<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Школа:</td><td>'.$rs['high_school'].'</td></tr>';
			if($userId==$profileId)
				$editUrl	= '<a href="'.base_url().'edit/education" style="text-decoration:none;">[ редагувати ]</a>';
			if($eduInfo!="")
				{
				$title	= '<tr><td colspan="2"><div class="profile_headline" style="padding-top: 10px;"><b>Освіта</b> '.$editUrl.'</div></td></tr>'.$eduInfo;
				}
				
			return $title;
		}//eduInformation()

	function workInformation($profileId,$userId)
		{
			$content	= '';
			$workInfo	= $this->getWorkInfo($profileId,$userId);
			
			if($workInfo!='') {
			if($userId==$profileId)
					$editUrl	= '<a href="'.base_url().'edit/work" style="text-decoration:none;">[ редагувати ]</a>';
			
				$content	= '<tr><td colspan="2"><div class="profile_headline" style="padding-top: 10px;"><b>Робота</b> '.$editUrl.'</div></td></tr>'.$workInfo;
			}
			return $content;
		}//workInformation()

	function getWorkInfo($profileId,$userId)
		{
			$content= '';
			$query	= 	"SELECT
							employer,position,description,city,start_month,start_year,end_month,end_year
						FROM work_profile
						WHERE user_id='$profileId'";
			$res	= mysql_query($query);
			$totRec	= mysql_num_rows($res);
			if($totRec>0)
				{
					$content= '';
					while($rs=mysql_fetch_object($res))
						{
							$content	.=	'<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Роботодавець:</td><td>'.$rs->employer.'</td></tr>';
							if($rs->position!='')
								$content	.=	'<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Посада:</td><td>'.$rs->position.'</td></tr>';
							if($rs->description!='')
								$content	.=	'<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Опис:</td><td>'.$rs->description.'</td></tr>';
							if($rs->city!='')
								$content	.=	'<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Місто:</td><td>'.$this->getCity($rs->city).'</td></tr>';
							
							if ($rs->start_month != '' and $rs->start_year != '')
							$startPeriod	= $rs->start_month.'.'.$rs->start_year;
							
							if ($rs->end_month != '' and $rs->end_year != '')
							$endPeriod		= $rs->end_month.'.'.$rs->end_year;
							
							$mn["01"]  = "січня";
							$mn["02"]  = "лютого";
							$mn["03"]  = "березня";
							$mn["04"]  = "квітня";
							$mn["05"]  = "травня";
							$mn["06"]  = "червня";
							$mn["07"]  = "липня";
							$mn["08"]  = "серпня";
							$mn["09"]  = "вересня";
							$mn["10"]  = "жовтня";
							$mn["11"]  = "листопада";
							$mn["12"]  = "грудня";
												
							if(trim($startPeriod)!='' and trim($endPeriod)!='')
								{
									$period		= 	'з '.$mn[date("m", mktime(0,0,0,$rs->start_month,1,0))].' '.$rs->start_year.' р. до '.$mn[date("m", mktime(0,0,0,$rs->end_month,1,0))].' '.$rs->end_year.' р.';
									$content	.=	'<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Період:</td><td>'.$period.'</td></tr>';
								}
							else if (trim($endPeriod) == '') 
							{
									$periodStart = explode(".", $startPeriod);
									$period		= 'з '.$mn[date("m", mktime(0,0,0,$rs->start_month,1,0))].' '.$rs->start_year.' р. і дотепер';
									$content	.=	'<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Період:</td><td>'.$period.'</td></tr>';
							}
							else if (trim($startPeriod) == '') 
							{
									$period		= 'до '.$mn[date("m", mktime(0,0,0,$rs->end_month,1,0))].' '.$rs->end_year.' р.';
									$content	.=	'<tr><td style="padding-right: 10px;" valign="top" nowrap="nowrap" class="fieldname">Період:</td><td>'.$period.'</td></tr>';
							}
							
							if($content!='')
								$content	.= '<tr><td colspan="2"><br></td></tr>';

						}//end while
				}//end res
			return $content;
		}//workInformation()

	function showFriends($profileId,$userId)
		{
			$totFriends	= count($this->common->getFriends($profileId));
			//$totFriends	= getTotRec("friend_id","friends_list", "user_id='$profileId' AND approved_status='yes'");//get total friends for this profile id(user_id)
			if($totFriends>0)
				{
					$query		= "	SELECT friend_id AS friend_id FROM `friends_list` WHERE user_id='$profileId' and approved_status='yes'
									UNION
									SELECT user_id as friend_id FROM `friends_list` WHERE friend_id='$profileId' and approved_status='yes' LIMIT 0,6";
					$res		= mysql_query($query);
					$seeAll	= base_url()."friends/view/".$profileId;//url to show all friends for this profile id
					$loop		= 1;
					$imgContent	= '<ul class="list">';
					while($rs=mysql_fetch_object($res))
						{
							$profileUrl	= base_url()."user/profile/".$rs->friend_id;
							$imagePath	= $this->common->getAvatar($rs->friend_id);		//function which returns the avatar of the given userid
							$username	= explode(" ", $this->common->getUsername($rs->friend_id));
							$imgContent	.='<li><div><a href="'.$profileUrl.'"  class="addToolTip" title="'.$username[0].' '.$username[1].'"><img src="'.$imagePath.'" width="60" height="60" border="0" /></a></div></li>';
							if($loop==3)//execute loop for show 3 friends per line
								{
									$loop=1;
									$imgContent	.='</ul><ul class="list">';
								}
							else
								$loop++;
						}//end while
					$imgContent	= '<ul class="list">'.$imgContent.'</ul>';
					$content	= '<h3 class="green">Друзі <a href="'.$seeAll.'">('.$totFriends.')</a></h3>'.$imgContent;

				}
			else
				$content	= '';
			return $content;
		}//end showFriends()	

	function showOnlineFriends($profileId,$userId)
		{
					$friendsList	= $this->common->onlineFriends($profileId);
					$count_online	=	count($friendsList);
					$seeAll	= base_url()."friends/online/".$profileId;
					
					$content = '';
					$loop		= 1;
					$imgContent	= '<ul class="list">';
					if(!empty($friendsList))
						{
							for($i = 0; $i < count($friendsList); $i++) {
								$imgContent	.=	$this->common->getOnlineFriends($friendsList[$i]);
								
							if($loop==3)//execute loop for show 3 friends per line
								{
									$loop=1;
									$imgContent	.='</ul><ul class="list">';
								}
							else
								$loop++;
								
							}
					
					$imgContent	= '<ul class="list">'.$imgContent.'</ul>';
					
					$content	= '
					

					<h3 class="yellow">Друзі онлайн <a href="'.$seeAll.'">('.$count_online.')</a></h3>'.$imgContent;
							
						} 
			return $content;
		}//end showFriends()				


	function showActions($profileId,$userId)
		{
			$content 	= '<table width="100%">';
			
			if ($profileId == $userId) {
				$content .= '<tr><td> &mdash; <a href="'.base_url().'edit/general">Редагувати мою сторінку</a></td></tr>';
			} else {
				$content .= '<tr><td class="profile_menu1" nowrap="nowrap"> <a href="'.base_url().'messages/compose/'.$profileId.'"><img src="'.base_url().'application/templates/images/icons/sendmessage16.gif" class="icon" border="0">Надіслати повідомлення</a></td></tr>';
			}
			
			$alreadyExist	= getTotRec("friends_list_id", "friends_list", "user_id='$userId' AND friend_id='$profileId' AND approved_status='yes'");
			$alreadyExist2	= getTotRec("friends_list_id", "friends_list", "user_id='$userId' AND friend_id='$profileId' AND approved_status='no'");
			
			if($alreadyExist>0 && $profileId != $userId) {
				$content .= '<tr><td class="profile_menu1"> <a href="'.base_url().'friends/remove/'.$profileId.'"><img src="'.base_url().'application/templates/images/icons/remove_friend16.gif" class="icon" border="0">Видалити з друзів</a></td></tr>';
			} elseif($alreadyExist2>0) {
				$content .= '<tr><td class="profile_menu1"> <a href="'.base_url().'friends/rejectout/'.$profileId.'"><img src="'.base_url().'application/templates/images/icons/remove_friend16.gif" class="icon" border="0">Відхилити запит на дружбу</a></td></tr>';
			} elseif($profileId != $userId) { 
				$content .= '<tr><td class="profile_menu1"> <a href="'.base_url().'friends/add/'.$profileId.'"><img src="'.base_url().'application/templates/images/icons/addfriend16.gif" class="icon" border="0">Додати до друзів</a></td></tr>';
			}
			
			$content .= '</table>';
			return $content;					
		}

	function showWall($profileId,$userId)
		{
			$this->load->helper('typography');
			$this->load->helper('smiley');

			$currentPage	= base_url();
			
			$profileId	= $this->uri->segment(3);
			$query	= "SELECT profile_wall_id, wall_post,posted_by, posted_to,datestamp FROM profile_wall WHERE posted_to='$profileId' ORDER BY datestamp DESC ";
			$res	= mysql_query($query);
			
					if($res)
						{
							while($rs=mysql_fetch_object($res))
								{
									$delId 		= $rs->profile_wall_id;
									$postDate	= date('d.m.Y',$rs->datestamp);
									$postTime	= date('h:i',$rs->datestamp);
									
									$postedBy		= $this->common->getUsername($rs->posted_by);
									$profileUrl		= base_url().'user/profile/'.$rs->posted_by;
									$face2faceUrl	= base_url().'user/face2face/'.$rs->posted_by.'/'.$profileId;

									$privatemsgUrl = '<font style="color: #ccc;">|</font> <a href="'.base_url().'messages/compose/'.$rs->posted_by.'">приватне повідомлення</a>';							
									$post2wallUrl = '<font style="color: #ccc;">|</font> <a href="'.base_url().'profile/post2wall/'.$rs->posted_by.'">написати на стіні</a>';							
									$delwallpost = '<font style="color: #ccc;">|</font> <a href="javascript:void(0);" style="text-decoration:none;" onclick="javascript:wallMsgDelete(\''.$delId.'\', \''.$profileId.'\', \''.$rs->posted_by.'\', \''.$currentPage.'\');">видалити</a>';
									
									$delpost = '';
									$prmsg = '';
									
									if ($profileId == $userId || $userId == $rs->posted_by ) {
										$delpost .= $delwallpost;
									}
									elseif ($profileId != $userId || $userId != $rs->posted_by ) {
										$prmsg .= $privatemsgUrl;
									}
									
									$content	.= '<li id="comment">
													<div class="comment-author">
													<a href="'.$profileUrl.'"><b>'.$postedBy.'</b></a> <span class="commdate" >'.$postDate.' @ '.$postTime.'</span> '.$this->common->offline($rs->posted_by, 'wall').' </div>
													<div class="comment-text ">'.parse_smileys(nl2br_except_pre($rs->wall_post), "http://demo.maax.ws/application/images/smileys/").'&nbsp;
													<p id="walloptions"><small><a href="'.$face2faceUrl.'">віч-на-віч</a> '.$post2wallUrl.' '.$prmsg.' '.$delpost.' </small></p>
													</div>
													</li>';
								}//end while
						}
						
						$userAvatar	= $this->common->getAvatar($profileId);						
						$postInterface	= $this->postWall2Profile($userId,$profileId);
						
						$content	= '
							<div id="wall_post_result">
							<div id="profile_postcomment">
							'.$postInterface.'<table width="100%"><ol class="commentlist">'.$content.'</ol></table></div>';

			return $content;
		}//showWall()
		
	function post2wall($postedto)
		{
			$this->loadSettings();
			$datas	= $this->common->authenticate();
			global $userId,$now;
			if(count($datas)<1)
				{
					$datas	= $this->common->basicvars();
					$data	= $datas;
					$data['siteUrl']		= site_url();
					$data['center_login']	= true;
					$this->smartyextended->view('login',$data);
				}
			else
				{

					$data		= array();
					$data		= $datas;
					
					$data['count_friends_request']	= $this->common->countFriendRequest($userId);
					$data['count_new_msg']	= $this->common->countNewMsg($userId);
					$data['count_wall_msg']	= $this->common->countWallMsg($profileId);
					$data['count_out_request']	= $this->common->countOutRequest($userId);
					
					
					$isPhotoExist	= getTotRec("picture_id","picture_profile","picture_path<>'' AND user_id='$userId'");
					if($isPhotoExist) {
					$data['mini_avatar']		= '<img src="'.$this->common->getAvatar($userId).'" width="30" class="userpic" border="0">';//отримання фото користувача
					} else {
					$data['mini_avatar']		= '<img src="'.$this->common->getAvatar($userId).'" width="30" class="userpic" border="0">';//отримання фото користувача
					}
					
					$profileId	= $this->uri->segment(3);
					
						$postInterface	= $this->postWall2Wall($userId,$profileId);
						$profileUrl	= base_url().'user/profile/'.$postedto;
						
						$content	= '
						<div class="page_header">Новий запис на стіні (<a href="'.$profileUrl.'">'.$this->common->getUsername($postedto).'</a>) </div>
						<p><a href="javascript: history.go(-1)">&larr; повернутись назад</a></p>
							<div id="wall_post_result">
							<div id="profile_postcomment">
							'.$postInterface.'</div>';


						$data['post2wall_content']	= $header.$content;
						$data['post2wall']			= true;
						$this->smartyextended->view('user/profile',$data);
			}
		}
			
		
	function face2face($postedby, $postedto)
		{
			$this->load->helper('typography');
			$this->load->helper('smiley');
			
			$this->loadSettings();
			$datas	= $this->common->authenticate();
			global $userId,$now;
			if(count($datas)<1)
				{
					$datas	= $this->common->basicvars();
					$data	= $datas;
					$data['siteUrl']		= site_url();
					$data['center_login']	= true;
					$this->smartyextended->view('login',$data);
				}
			else
				{

					$data		= array();
					$data		= $datas;
					
					$data['count_friends_request']	= $this->common->countFriendRequest($userId);
					$data['count_new_msg']	= $this->common->countNewMsg($userId);
					$data['count_wall_msg']	= $this->common->countWallMsg($profileId);
					$data['count_out_request']	= $this->common->countOutRequest($userId);
					
					
					$isPhotoExist	= getTotRec("picture_id","picture_profile","picture_path<>'' AND user_id='$userId'");
					if($isPhotoExist) {
					$data['mini_avatar']		= '<img src="'.$this->common->getAvatar($userId).'" width="30" class="userpic" border="0">';//отримання фото користувача
					} else {
					$data['mini_avatar']		= '<img src="'.$this->common->getAvatar($userId).'" width="30" class="userpic" border="0">';//отримання фото користувача
					}
					
					$profileId	= $this->uri->segment(3);
					
					$query	= "
					SELECT * FROM `profile_wall` WHERE posted_by='$postedby' AND posted_to='$postedto' 
					UNION
					SELECT * FROM `profile_wall` WHERE posted_by='$postedto' AND posted_to='$postedby' 
					ORDER BY datestamp DESC";
					$res	= mysql_query($query);
					if($res)
						{
							$totRec	= mysql_num_rows($res);
							while($rs=mysql_fetch_object($res))
								{
									$postDate	= date('d.m.Y',$rs->datestamp);
									$postTime	= date('h:i',$rs->datestamp);
									
									$postedBy	= $this->common->getUsername($rs->posted_by);
									$post2wallUrl = '<a href="'.base_url().'user/post2wall/'.$rs->posted_by.'">написати на стіні</a>';							
									$profileUrl	= base_url().'user/profile/'.$rs->posted_by;
									$privatemsgUrl = '<font style="color: #ccc;">|</font> <a href="'.base_url().'messages/compose/'.$rs->posted_by.'">приватне повідомлення</a>';							

									$prmsg = '';
									if ($userId != $rs->posted_by ) {
										$prmsg .= $privatemsgUrl;
									}
									
									
									$content	.= '<li id="comment">
													<div class="comment-author">
													<a href="'.$profileUrl.'"><b>'.$postedBy.'</b></a> <span class="commdate" >'.$postDate.' @ '.$postTime.'</span> '.$this->common->offline($rs->posted_by, 'wall').' </div>
													<div class="comment-text ">'.parse_smileys(nl2br_except_pre($rs->wall_post), "http://demo.maax.ws/application/images/smileys/").'&nbsp;
													<p id="walloptions"><small>'.$post2wallUrl.' '.$prmsg.'</small></p>
													</div>
													</li>';
								}//end while
						}

						$content	= '
							<div id="wall_post_result">
							<div id="profile_postcomment">
							<div class="page_header">Віч-на-віч між <a href="'.base_url().'user/profile/'.$postedby.'">'.$this->common->getUsername($postedby).'</a> і <a href="'.base_url().'user/profile/'.$postedto.'">'.$this->common->getUsername($postedto).'</a></div>
							<a href="javascript: history.go(-1)">&larr; повернутись назад</a>
							<table width="100%"><ol class="commentlist">'.$content.'</ol></table></div>';


						$data['face2face_content']	= $header.$content;
						$data['face2face']			= true;
						$this->smartyextended->view('user/profile',$data);
			}
		}
			
		
	function postWall2Profile($postedBy,$postedTo)
		{
			$this->load->helper('smiley');
			$this->load->library('table');
		
			$currentPage	= base_url();
			$ajaxLoader		= base_url().'/application/images/ajax-loader.gif';
			
			$image_array = get_clickable_smileys('http://demo.maax.ws/application/images/smileys/');
			$col_array = $this->table->make_columns($image_array, 17);		
			$smiley_table = $this->table->generate($col_array);
			$insert_smiley = js_insert_smiley("wall_form", "post_content");
			
			$content	= '
							<div id="wall_post_ajax_loader" style="display:none; padding: 5px;" align="center"><img src="'.$ajaxLoader.'"></div>
							<form name="wall_form" method="post">
							<div id="wall_post_result2"></div>
							<div class="profile_postcomment">
							<textarea style="overflow: hidden; height: 70px; color: rgb(136, 136, 136);" name="post_content" id="post_content" cols="25" class="comment_area" onkeypress="ctrlEnterWall(event);"></textarea>
							'.$insert_smiley.$smiley_table.'
							<div style="text-align: right; margin-top: 5px;">
							<input type="button" name="post_wall" id="post_wall" class="button" value="Надіслати" onclick="post2Profile(\''.$postedBy.'\',\''.$postedTo.'\',\''.$currentPage.'\',\''.$type.'\');">
							</div>
							</form>
							</div></div>';
			return $content;
		}//postWall2Profile()		

	function postWall2Wall($postedBy,$postedTo)
		{
			$this->load->helper('smiley');
			$this->load->library('table');
		
			$currentPage	= base_url();
			$ajaxLoader		= base_url().'/application/images/ajax-loader.gif';
			
			$image_array = get_clickable_smileys('http://demo.maax.ws/application/images/smileys/');
			$col_array = $this->table->make_columns($image_array, 22);		
			$smiley_table = $this->table->generate($col_array);
			$insert_smiley = js_insert_smiley("wall_form", "post_content");
			
			$content	= '
							<div id="wall_post_ajax_loader" style="display:none; padding: 5px;" align="center"><img src="'.$ajaxLoader.'"></div>
							<form name="wall_form" method="post">
							<div id="wall_post_result2"></div>
							<div class="profile_postcomment">
							<textarea style="overflow: hidden; height: 70px; color: rgb(136, 136, 136);" name="post_content" id="post_content" cols="25" class="comment_area" onkeypress="ctrlEnterWall(event);"></textarea>
							'.$insert_smiley.$smiley_table.'
							<div style="text-align: right; margin-top: 5px;">
							<input type="button" name="post_wall" id="post_wall" class="button" value="Надіслати" onclick="post2Wall(\''.$postedBy.'\',\''.$postedTo.'\',\''.$currentPage.'\',\''.$type.'\');">
							</div>
							</form>
							</div></div>';
			return $content;
		}//postWall2Profile()		
		
	function loadSettings()
		{
			global $userId,$now,$adminName,$adminEmail,$siteName,$siteTitle;
			$this->load->model('common');

			$userId		= $this->session->userdata('user_id');
			$now		= $this->config->item('now');

			$siteVars	= $this->common->getSiteVars();
			$adminName	= $siteVars['adminName'];
			$adminEmail	= $siteVars['adminEmail'];
			$siteName	= $siteVars['siteName'];
			$siteTitle	= $siteVars['siteTitle'];
		}
}
?>